package com.xiyu.service.framework.mail.sync;

import cn.hutool.core.util.StrUtil;
import com.xiyu.service.enums.market.task.MarketTaskMailInvalidTypeEnum;
import com.xiyu.service.model.market.task.*;
import com.xiyu.service.repository.market.task.MarketTaskReceiverRepository;
import com.xiyu.service.repository.market.task.MarketTaskRepository;
import com.xiyu.service.repository.market.task.MarketTaskWebhookLogRepository;
import com.xiyu.service.vo.infra.sendCloud.SendCloudReceiveInput;
import jakarta.annotation.Resource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class SyncWebhookInfo {

    @Resource
    MarketTaskWebhookLogRepository marketTaskWebhookLogRepository;

    @Resource
    MarketTaskRepository marketTaskRepository;

    @Resource
    MarketTaskReceiverRepository marketTaskReceiverRepository;

    @Async
    public void saveWebhookInfo(SendCloudReceiveInput inputVO){
        if(inputVO.getEvent().equals("request")){

            String[] emailIds = convertEmailIds(inputVO.getEmailIds());
            for(String emailId : emailIds){
                handleEvent(inputVO, emailId, "request");
            }
        }else{
            handleEvent(inputVO, inputVO.getEmailId(), inputVO.getEvent());
        }
    }

    String[] convertEmailIds(String strEmailIds){
        return strEmailIds
                .replace("[", "")
                .replace("]", "")
                .replace("\"", "")
                .split(",");
    }

    private void handleEvent(SendCloudReceiveInput inputVO, String emailId, String event){

        if(emailId == null){
            errorLog(inputVO, "emailId为null");
            return;
        }
        MarketTaskReceiver receiver = marketTaskReceiverRepository.findByMarketMailId(emailId).orElse(null);
        if(receiver == null){
            errorLog(inputVO, "找不到对应的receiver");
            return;
        }
        MarketTask marketTask = marketTaskRepository.findNullable(receiver.taskId());
        if(marketTask == null){
            errorLog(inputVO, "找不到对应的task");
            return;
        }
        switch (event){
            case "request":
                if(!receiver.isRequest()){
                    receiver = MarketTaskReceiverDraft.$.produce(receiver, draft -> draft.setIsRequest(true));
                    marketTaskRepository.updateRequestCount(marketTask.id(), marketTask.requestCount() + 1);
                }
                break;
            case "deliver":
                if(!receiver.isDeliver()){
                    receiver = MarketTaskReceiverDraft.$.produce(receiver, draft -> draft.setIsDeliver(true));
                    marketTaskRepository.updateDeliverCount(marketTask.id(), marketTask.deliverCount() + 1);
                }
                break;
            case "open":
                if(!receiver.isOpen()){
                    receiver = MarketTaskReceiverDraft.$.produce(receiver, draft -> draft.setIsOpen(true));
                    marketTaskRepository.updateOpenCount(marketTask.id(), marketTask.openCount() + 1);
                }
                break;
            case "click":
                if(!receiver.isClick()){
                    receiver = MarketTaskReceiverDraft.$.produce(receiver, draft -> draft.setIsClick(true));
                    marketTaskRepository.updateClickCount(marketTask.id(), marketTask.clickCount() + 1);
                }
                break;
            case "route":
                if(!receiver.isReply()){
                    receiver = MarketTaskReceiverDraft.$.produce(receiver, draft -> draft.setIsReply(true));
                    marketTaskRepository.updateReplyCount(marketTask.id(), marketTask.replyCount() + 1);
                }
                break;
            case "invalid":
                if(!receiver.isInvalid()){
                    receiver = MarketTaskReceiverDraft.$.produce(receiver, draft -> draft.setIsInvalid(true)
                            .setInvalidType(MarketTaskMailInvalidTypeEnum.HARD.getValue()).setInvalidReason("硬退信：" + inputVO.getSubStatDesc())
                    );
                    marketTaskRepository.updateInvalidCount(marketTask.id(), marketTask.invalidCount() + 1);
                }
                break;
            case "soft_bounce":
                if(!receiver.isInvalid()){
                    receiver = MarketTaskReceiverDraft.$.produce(receiver, draft -> draft.setIsInvalid(true)
                            .setInvalidType(MarketTaskMailInvalidTypeEnum.SORT.getValue()).setInvalidReason("软退信：" + inputVO.getSubStatDesc())
                    );
                    marketTaskRepository.updateInvalidCount(marketTask.id(), marketTask.invalidCount() + 1);
                }
                break;

        }
        marketTaskReceiverRepository.update(receiver);
    }

    private void errorLog(SendCloudReceiveInput inputVO, String error){
        if(inputVO != null){
            MarketTaskWebhookLog log = MarketTaskWebhookLogDraft.$.produce(draft -> draft
                    .setApiUser(inputVO.getApiUser()).setErrorMessage(StrUtil.sub(error, 0, 1024))
                    .setEvent(inputVO.getEvent()).setRequest(inputVO.toString())
            );
            marketTaskWebhookLogRepository.insert(log);
        }

    }
}
